<?php

namespace app\modules\weixin\controllers;

use app\common\services\StaticServices;
use app\models\IntegralRecord;
use app\models\Member;
use app\models\MemberIntegral;
use app\models\MemberNotice;
use app\models\Recommend;
use app\modules\weixin\controllers\common\BaseController;
use Yii;
use yii\base\Exception;
use yii\web\Response;

class MemberController extends BaseController
{
    /**
     * 个人中心
     * @return array
     */
    public function actionCenter()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->get('member_id'));
            $session_member_info = Yii::$app->session->get('member_info');
            if (!$member_id || $member_id != $session_member_info['id']) {
                throw new Exception('参数有误');
            }
            $member_info = Member::find()->where(['id' => $member_id])->one();
            $member_user_integral = StaticServices::getMemberUseIntegral($member_id);
            $member_total_integral = intval($member_user_integral) + intval($member_info->member_integral);
            $record_count = IntegralRecord::getNoExchange($member_id);
            $data = [
                'member_user_integral' => $member_user_integral,
                'member_total_integral' => $member_total_integral,
                'record_count' => $record_count,
                'member_integral' => $member_info->member_integral,
                'member_name' => $session_member_info['member_name'],
            ];
            return ['code' => 200, 'data' => $data];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * 公告
     * @return array
     */
    public function actionNotice()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $p = intval(Yii::$app->request->get('p', 1));
            $notice_info = MemberNotice::find()->where(['notice_status' => 1]);

            $page_size = 5;
            $total_count = $notice_info->count();
            $total_page = ceil($total_count / $page_size);

            $list = $notice_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->asArray()->all();
            foreach ($list as &$item) {
                $item['notice_content'] = strip_tags($item['notice_content']);
            }
            $list['total_page'] = $total_page;
            return ['code' => 200, 'data' => $list];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * 积分流水
     * @return array
     */
    public function actionIntegralDetails()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->post('member_id'));
            $integral_type = Yii::$app->request->post('integral_type');
            $p = intval(Yii::$app->request->post('p', 1));

            if (!$member_id) {
                throw new Exception('参数有误');
            }

            $page_size = 5;

            if ($integral_type == 'use') {
                $use_integral = IntegralRecord::find()->joinWith('good')->where(['member_id' => $member_id]);

                $total_count = $use_integral->count();
                $total_page = ceil($total_count / $page_size);

                $list = $use_integral->offset(($p - 1) * $page_size)->orderBy(['create_time' => SORT_DESC])->limit($page_size)->asArray()->all();
                $list['total_page'] = $total_page;
                return ['code' => 200, 'data' => $list];
            }

            if ($integral_type == 'get') {
                $get_integral = MemberIntegral::find()->where(['member_id' => $member_id]);

                $total_count = $get_integral->count();
                $total_page = ceil($total_count / $page_size);

                $list = $get_integral->offset(($p - 1) * $page_size)->orderBy(['create_time' => SORT_DESC])->limit($page_size)->asArray()->all();
                $list['total_page'] = $total_page;
                return ['code' => 200, 'data' => $list];
            }
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 会员推荐好友
     */
    public function actionInvitation()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_name = trim(Yii::$app->request->post('member_name'));
            $member_phone = trim(Yii::$app->request->post('member_phone'));
            $member_id = intval(Yii::$app->request->post('member_id'));
            $remark = trim(Yii::$app->request->post('remark'));
            $session_member = Yii::$app->session->get('member_info');

            if (!$member_id || $member_id != $session_member['id']) {
                throw new Exception('参数有误');
            }

            if (!$member_name) {
                throw new Exception('用户名不能为空');
            }
            if (mb_strlen($member_phone, 'utf-8') != 11 && !preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $member_phone)) {
                throw new Exception('请填写正确的手机号码');
            }

            $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
            if ($member_info) {
                throw new Exception('此用户已经被邀请了');
            }

            $default_pwd = strtolower(StaticServices::getRandChar(6));
            $member_arr = new Member();
            $member_arr->member_name = $member_name;
            $member_arr->member_phone = $member_phone;
            $member_arr->member_pwd = $default_pwd;
            $member_arr->recommend_id = $member_id;
            $member_arr->update_time = time();
            $member_arr->create_time = time();
            if ($member_arr->save(0)) {
                $recommend = new Recommend();
                $recommend->member_id = $member_arr->id;
                $recommend->member_name = $member_name;
                $recommend->recommend_id = $member_id;
                $recommend->recommend_name = $session_member['member_name'];
                $recommend->recommend_source = 2;
                $recommend->recommend_type = 0;
                if ($remark) {
                    $recommend->remark = $remark;
                }
                $recommend->update_time = time();
                $recommend->create_time = time();
                $recommend->save(0);
            }
            return ['code' => 200, 'msg' => '推荐成功'];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    public function actionMemberInfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->get('member_id'));
            if (!$member_id) {
                throw new Exception('参数有误');
            }
            $member_info = Member::find()->select('member_phone,member_name')->where(['id' => $member_id])->asArray()->one();
            $recommend_info = Recommend::find()->select('id,remark,recommend_name')->where(['member_id' => $member_id])->one();
            $member_info['remark'] = $recommend_info->remark;
            $member_info['recommend_name'] = $recommend_info->recommend_name;
            if (!$member_info) {
                throw new Exception('数据有误');
            }
            return ['code' => 200, 'msg' => '操作成功', 'data' => $member_info];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }
}
